<?php

/**
 * This is the model class for table "indicator".
 *
 * The followings are the available columns in table 'indicator':
 * @property integer $id
 * @property string $name
 * @property integer $item_id
 * @property string $over_view
 * @property string $over_reason
 * @property string $under_reason
 * @property string $cure_care
 * @property string $expert_advice
 * @property string $value_ranges
 *
 * The followings are the available model relations:
 * @property ExamItem $item
 */
class Indicator extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Indicator the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'info_indicator';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('item_id', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>255),
			array('over_view, over_reason, under_reason, cure_care, expert_advice, value_ranges', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name, item_id, over_view, over_reason, under_reason, cure_care, expert_advice, value_ranges', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'item' => array(self::BELONGS_TO, 'ExamItem', 'item_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => '体检指标名称',
			'item_id' => '所属体检项',
			'over_view' => '概述',
			'over_reason' => '偏高原因',
			'under_reason' => '偏低原因',
			'cure_care' => '治疗保健',
			'expert_advice' => '专家建议',
			'value_ranges' => '取值范围',
		);
	}
    
    public function getSubIndicatorOfItem($item_id)
    {
   		$ret = array();
		$criteria=new CDbCriteria;
		$criteria->select="id";
        $criteria->condition = "item_id=:item_id";
        $criteria->params=array(':item_id'=>$item_id);
		$rows = $this->findAll($criteria);
		$ret = array();
		for($i = 0; $i < count($rows); $i++)
		{
			$row = $rows[$i];
			$id = $row->id;
            array_push($ret, $id);
		}
		return $ret;
    }

	public function getAllIndicators()
	{
		$ret = array();
		$criteria=new CDbCriteria;
		$criteria->select="id, name";
		$rows = $this->findAll($criteria);
		$ret = array();
		for($i = 0; $i < count($rows); $i++)
		{
			$row = $rows[$i];
			$id = $row->id;
			$name = $row->name;
			$ret[$id]=$name;
		}
		return $ret;
	}
	
	/**
	 * search the indicator by names.
	 * @param: keyword that used to mathc indicator name or its related item name
	 * @return array of (item_id, item_name, indicator_id, indicator_name)
	 */
	public function searchOnlyIndicatorByKeyword($kw)
	{
		$conn = Yii::app()->db;
		$sql = $conn->createCommand()
					->from('info_indicator')
					->order('item_id');
		if(strcmp($kw, "*")!=0)
		{
			$sql = $sql->where(array('like','name','%'.$kw.'%'));
		}
		$rows = $sql->queryAll();
                $items = array();
		foreach($rows as $row){
                    $item["id"] = $row["id"];
                    $item["name"] = $row["name"];
                    array_push($items, $item);
                }
		
		return $items;
	}
        public function searchByKeyword($kw)
	{
            $conn = Yii::app()->db;
		$sql = $conn->createCommand()
					->select('a.id as item_id, a.item_name as item_name, b.id as indicator_id, b.name as indicator_name')
					->from('info_exam_item  a')
					->join('info_indicator b', 'a.id=b.item_id')
					->order('item_id');
		
		if(strcmp($kw, "*")!=0)
		{
                        $sql = $sql->where(array('like','a.item_name','%'.$kw.'%')) 
						->orWhere(array('like', 'b.name','%'.$kw.'%'));
		}
		$rows = $sql->queryAll();
		//echo json_encode($rows);
		$hirachyArray = $this->constructLevelArray($rows);
		return $hirachyArray;
	}
	
	private function constructLevelArray($rows)
	{
		$retArray = array();
		$lastItemId=-1;
		$curRowArray = array();
		for($i = 0; $i < count($rows); $i++)
		{
			$row = $rows[$i];
			$curItemId = $row["item_id"];
			//echo $curItemId;
			if($curItemId != $lastItemId)
			{
				if($lastItemId != -1)
				{
					array_push($retArray, $curRowArray);
				}
				$curRowArray = array();
				$curIndicatorArray = array();
				$curRowArray['item_id'] = $curItemId;
				$curRowArray['item_name'] = $row["item_name"];
				$curRowArray['indicator'] = $curIndicatorArray;
				$curIndicator = array('iid'=>$row["indicator_id"], 'iname' => $row["indicator_name"]);
				array_push($curRowArray['indicator'], $curIndicator);
				$lastItemId = $curItemId;
			}
			else
			{
				$curIndicator = array('iid'=>$row['indicator_id'], 'iname' => $row['indicator_name']);
				array_push($curRowArray['indicator'], $curIndicator);
			}
		}	
		if($lastItemId != -1)
		{
			array_push($retArray, $curRowArray);
		}
		return $retArray;
	}
	
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('item_id',$this->item_id);
		$criteria->compare('over_view',$this->over_view,true);
		$criteria->compare('over_reason',$this->over_reason,true);
		$criteria->compare('under_reason',$this->under_reason,true);
		$criteria->compare('cure_care',$this->cure_care,true);
		$criteria->compare('expert_advice',$this->expert_advice,true);
		$criteria->compare('value_ranges',$this->value_ranges,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}